<script>
import { uid } from 'quasar'
import { loadCdnSources } from 'src/utils/cdn.js'

export default {
  name: 'LocationMap',
  props: {
    point: {
      type: Array,
      required: true
    }
  },
  data () {
    return {
      containerId: uid(),
      map: null,
      layer: null
    }
  },
  watch: {
    point (point) {
      this.addPoint(point)
    }
  },
  mounted () {
    this.init()
  },
  methods: {
    async init () {
      await loadCdnSources()
      const { Map } = window.maptalks
      this.map = new Map(this.$el, {
        center: [104.07, 30.66],
        zoom: 15,
        minZoom: 10,
        maxZoom: 18,
        pitch: 0,
        bearing: 0,
        touchPitch: false,
        touchRotate: false,
        panAnimation: false,
        fpsOnInteracting: 15,
        zoomControl: false,
        doubleClickZoom: false,
        seamlessZoom: false,
        attribution: false,
        dragPitch: false,
        dragRotate: false
      })
      this.createTileLayer()
      this.addPoint(this.point)
    },
    createTileLayer () {
      const { TileLayer } = window.maptalks
      const options = {
        title: '街道',
        type: 'base',
        image: true,
        attribution: '高德地图',
        subdomains: ['1', '2', '3'],
        urlTemplate: 'http://webrd0{s}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}',
        zoomBackground: true
      }
      const layer = new TileLayer(uid(), options)
      layer.addTo(this.map)
    },
    async addPoint (coordinates) {
      const { VectorLayer, GeoJSON } = window.maptalks
      if (this.layer) {
        this.map.removeLayer(this.layer)
      }
      this.layer = new VectorLayer(uid(), { zIndex: 10000 })
      this.map.animateTo({ center: coordinates, duration: 500, easing: 'out' })
      GeoJSON.toGeometry({
        type: 'Feature',
        geometry: {
          type: 'Point',
          coordinates
        }
      }, (geometry) => {
        geometry.setSymbol({
          markerType: 'ellipse',
          markerWidth: 12,
          markerHeight: 12,
          markerLineWidth: 4,
          markerLineColor: '#000',
          markerFill: '#f00'
        })
      }).addTo(this.layer)
      this.layer.addTo(this.map)
    }
  }
}
</script>

<template>
  <div :id="containerId" class="full-height" />
</template>
